/**
 * getting the JSON object from servlet by creating a posting request
 * @param url : the URL of servlet
 */
function getJSONData(urlParameter, requestData) {
	var xhrArgs = {
			sync: true,
            url: urlParameter,
            content : {requestAction: requestData},
            handleAs: "json",
    		error: function(error) {
    		}
    };
	return dojo.xhrPost(xhrArgs);
}

/**
 * get a color string with a given index
 * @param index
 * @returns : color string
 */
function getChartColor(index) {
	var colorList = ["red", "orange", "yellow", "blue", "green", "purple", "brown", "darkyellow", "darkblue", "darkgreen"];
	return colorList[index];
}

/**
 * extract the data in table for labeling x axis and data of y axis
 * the key in data table will be labels in x axis and the value will be the data of y axis
 * @param dataTable : hash table contains labels for x axis(key) and data of y axis(value)
 * @param xAxisLabels : an array of x axis' labels
 * @param yAxis1 : the first array of data (Capacity) shown in the y axis
 * @param yAxis2 : the second array of data (Sold_Seats or Total_Amount) shown in the y axis
 * @returns {Number} : the biggest number in y axis, this will influence the range of columns
 */
function generateColumnData(dataTable, xAxisLabels, yAxis1, yAxis2, yAxis3) {
	var max = 0;
	var keyArray = Object.keys(dataTable).sort();
	var counter = 1;
	for(var index in keyArray) {
		var key = keyArray[index];
		var data = dataTable[key];
		var tmp = {};
		tmp.value = counter++;
		tmp.text = key;
		xAxisLabels.push(tmp);
		if(max < data[0])
			max = data[0];
		if(max < data[1])
			max = data[1];
		var yTmp1 = {};
		var yTmp2 = {};
		var yTmp3 = {};
		yTmp1.y = data[0];
		yTmp2.y = data[1];
		yTmp3.y = data[2];
		if(yTmp1.y > 0)
			yTmp1.fill = "red";
		else
			yTmp1.fill = "white";
		yTmp2.fill = "green"; 
		yTmp3.fill = "blue";
		yAxis1.push(yTmp1);
		yAxis2.push(yTmp2);
		yAxis3.push(yTmp3);
	}
	return max;
}

/**
 * Get the (x, y) data pairs for showing the pie chart
 * @param dataTable : hash tables which contains the pairs of (x, y) (e.g. x : ticket_level, y : sold total amount)
 * @returns {Array} : a list of hashmap [{x : xValue1, y : yValue1}, {x : xValue2, y : yValue2}]
 */
function generatePieData(dataTable) {
	var dataItems = [];
	var counter = 0;
	var keyArray = Object.keys(dataTable).sort();
	for(var index in keyArray) {
		key = keyArray[index];
		var data = dataTable[key];
		if(data[1] > 0) {
			var tmp = {};
			tmp.x = key;
			tmp.y = data[1];
			tmp.legend = key;
			tmp.color = getChartColor(counter);
			tmp.tooltip = key;
			dataItems.push(tmp);
			counter++;
		}
	}
	return dataItems;
}

/**
 * get the max value of data in y axis
 * @param yAxisData : total values in y axis
 * @returns {Number} : the max value in y axis
 */
function findMax(yAxisData) {
	var max = 0;
	for(var i = 0; i < yAxisData.length; i++) {
		if(yAxisData[i] > max)
			max = yAxisData[i];
	}
	return max;
}

/**
 * interpret the json string, get values from it and save them into a hash table
 * if the eventCode is equal to "ALL EVENT", the key for hash table should be each event's code
 * if the eventCode is a single match, the key should be different ticket level
 * @param jsonStr : json response from servlet
 * @param property : the property of values in json (e.g. Price, Sold_Seats, Total_Amount..)
 * @param eventCode : event code for all events(ALL EVENT) or a single match
 * @returns {___anonymous1933_1934} : hash table result
 */
function JSONToTable(jsonStr, property, eventCode) {
	var dataTable = {};
	for(var i = 0; i < jsonStr.items.length; i++) {
		var curr = jsonStr.items[i];
		if((eventCode == "ALL EVENT") || (curr.Event_Code == eventCode)) {
			var key = "";
			if(eventCode != "ALL EVENT") {
				key = curr.Ticket_Level_Name;
			}
			else
				key = curr.Event_Code;
			if(!dataTable.hasOwnProperty(key)) {
				var data = [];
				data.push(curr["Capacity"]);
				data.push(curr[property]);
				data.push(curr["Comp_Seats"]);
				dataTable[key] = data;
			}
			else {
				var data = dataTable[key];
				data[0] += curr["Capacity"];
				data[1] += curr[property];
				data[2] += (curr["Comp_Seats"]);
				//console.log(key);
				//console.log(dataTable[key]);
			}
		}
	}
	return dataTable;
}

/**
 * Get the biggest character key in the hash table which saves pairs of ticket level and data
 * @param dataTable : a hash table of ticket level and data
 * @returns {String} : the biggest character of key in dataTable
 */
function getMaxKey(dataTable) {
	var maxKey = 'A';
	for(var key in dataTable) {
		if(key > maxKey) {
			maxKey = key;
		}
	}
	return maxKey;
}

/**
 * create a legend for a chart
 * @param chart : an object of chart
 * @param legendId : id of legend
 */
function generateLegend(chart, legendId) {
	var widget = dijit.byId(legendId);
	if(widget)
		widget.destroy();
	new dojox.charting.widget.Legend({chart: chart}, legendId);
}

/**
 * fill the column chart with the data in json object according to different key in the items of json object
 * @param chart : dojo chart object
 * @param jsonStr : json string get from servlet
 * @param eventCode : the value of Event_Code in json's items
 * @param key : the key of json's items
 * 
 */
function fillColByKey(chart, jsonStr, eventCode, key) {
	var xAxisLabels = [];
	var yAxis1 = [];
	var yAxis2 = [];
	var yAxis3 = [];
	
	//get the data for the y axis in the column chart
	var axisTable = JSONToTable(jsonStr, key, eventCode);
	
	//extract the event code and price from hash table and add them into lists(xAxis and yAxis)
	var maxY = generateColumnData(axisTable, xAxisLabels, yAxis1, yAxis2, yAxis3) + 100;
	chart.addAxis("x", {majorLabels: true, majorTicks: true, majorTick: {length:1}, minorLabels: false, microTicks : false, labels : xAxisLabels});
    chart.addAxis("y", {title : key, vertical: true, includeZero: false, fixLower: "major", fixUpper: "major", min: 0, max: maxY, majorTick: {color: "black", length: 6}, minorTicks: true});

    console.log(yAxis1);
    console.log(yAxis2);
    console.log(yAxis3);
    if(key == "Sold_Seats") {
    	chart.addSeries("Comp_Seats", yAxis3);
    }
    chart.addSeries(key, yAxis2);
    if(key == "Sold_Seats") {
    	chart.addSeries("Capacity", yAxis1);
    }
	chart.render();
	generateLegend(chart, "columnLegend");
}

/**
 * get json string data from server, extract the sold seats information from json and show it on column charts
 * @param chart : a dojo chart object
 * @param eventCode : event code for a match
 */
function fillCol_Seats(chart, eventCode) {
	var deferred = getJSONData("/msgSp12/ActionController", "ticketGraph");
	//use the JSON data to generate the graph
	deferred.then(function(res) {
		fillColByKey(chart, res, eventCode, "Sold_Seats");
	});
}

/**
 * get json string data from server, extract the sold seats information from json and show it on column charts
 * @param chart : a dojo chart object
 * @param eventCode : event code for a match
 */
function fillCol_Sale(chart, eventCode) {
	var deferred = getJSONData("/msgSp12/ActionController", "ticketGraph");
	
	//use the JSON data to generate the graph
	deferred.then(function(res) {
		fillColByKey(chart, res, eventCode, "Total_Amount");
	});
}


function fillPie_Sale(chart, eventCode) {
	var deferred = getJSONData("/msgSp12/ActionController", "ticketGraph");
	
	//use the JSON data to generate the graph
	deferred.then(function(res) {
		var axisTable = JSONToTable(res, "Total_Amount", eventCode);
		//extract the event code and price from hash table and add them into lists(xAxis and yAxis)
		var items = generatePieData(axisTable);
		// Add the series of data
		chart.addSeries("Total Sold Amount of " + eventCode, items);
		chart.render();
		//generateLegend(chart, "columnLegend");
		generateLegend(chart, "pieLegend");
	});
}


function fillPie_Seats(chart, eventCode) {
	var deferred = getJSONData("/msgSp12/ActionController", "ticketGraph");
	//use the JSON data to generate the graph
	//use the JSON data to generate the graph
	deferred.then(function(res) {
		var axisTable = JSONToTable(res, "Sold_Seats", eventCode);
		//extract the event code and price from hash table and add them into lists(xAxis and yAxis)
		var items = generatePieData(axisTable);
		// Add the series of data
		chart.addSeries("Total Sold Seats of " + eventCode, items);
		chart.render();
		//generateLegend(chart, "columnLegend");
		generateLegend(chart, "pieLegend");
	});
}

/**
 * dynamically create the items shown in the combo box
 * @param res : the json object contains different key value pairs
 * @param events : the items in the event combo box(for selecting a event)
 * @param yAxisItem : the items in the yAxis combo box(for selecting the labels of y axis)
 */
function createComboItems(res, events, yAxisItem) {
	//create the items for selecting different event
	var eventTable = {};
	for(var i = 0; i < res.items.length; i++) {
		curr = res.items[i];
		if(!eventTable.hasOwnProperty(curr.Event_Code))
			eventTable[curr.Event_Code] = curr.Event_Code;
	}
	var tmp = {};
	tmp.name = "ALL EVENT";
	tmp.value = "ALL EVENT";
	events.push(tmp);
	for(var eventItem in eventTable) {
		var tmp = {};
		tmp.name = eventItem;
		tmp.value = eventItem;
		events.push(tmp);
	}
	var yItem_seats = {};
	yItem_seats.name = "Sold_Seats";
	yItem_seats.value = "Sold_Seats";
	yAxisItem.push(yItem_seats);
	var yItem_amount = {};
	yItem_amount.name = "Sold_Amount";
	yItem_amount.value = "Sold_Amount";
	yAxisItem.push(yItem_amount);
}

function addComboItems(ref, events) {
	for(var i = 0; i < events.length; i++) {
		var curr = events[i];
		var optn = document.createElement("OPTION");
		optn.text= curr.name;
		optn.value= curr.value;
		ref.options.add(optn);
		if(i == 0)
			optn.selected = true;
	}
}